package fr.emse.tatiana.commands;

import java.io.File;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;

import fr.emse.tatiana.CorpusNavigationView;


public class DeleteFileAction extends Action{
	

	private static DeleteFileAction instance;

	public static DeleteFileAction getInstance() {
		return instance;
	}


	private IWorkbenchWindow window;
	private String navigationId;

	public DeleteFileAction(IWorkbenchWindow window, String label, String navigationId) {
		this.window = window;
		this.navigationId = navigationId;
		setText(label);
		setId(ICommandIds.CMD_DELETE_FILE);
		setImageDescriptor(fr.emse.tatiana.Activator.getImageDescriptor("/icons/delete_obj.gif"));
		this.setEnabled(false);
		instance = this;
	}


	@Override
	public void run() {
		IStructuredSelection sel=((CorpusNavigationView) window.getActivePage().findView(this.navigationId)).getSelection();
		IPath path = ((IResource) sel.getFirstElement()).getLocation();
		
		IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.lastSegment());
		if (project.exists()) {
			MessageDialog.openError(window.getShell(),"Error","You can't delete a project");
			return;
		}
		
		boolean confirmation=MessageDialog.openConfirm(window.getShell(), "Delete File","This will delete the file from the project. Do you want to continue?");
		if(!confirmation){
			return;
		}
		else{
			
			File file=new File(path.toOSString());
			if(file.isFile()){
				file.delete();
			}
			else{
				suppr(file);
				file.delete();
			}
			try {
				ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void suppr(File r){
		File [] fileList = r.listFiles();
		for(int i = 0;i<fileList.length;i++){
			if(fileList[i].isDirectory() ){
				suppr(fileList[i]);
				fileList[i].delete();
			}else{
				fileList[i].delete();
			}
		}
	}
}
